import axios from 'axios';
import Toast from 'react-native-root-toast';
import storage, { load } from '@/config/storage';

const REQUEST_URL = '/login';


const initialState = {
    loging: false,
    user: undefined,
};

/**
 * 登录模块的model
 */
const PlayerModel = {
    namespace: 'login',
    state: initialState,
    reducers: {
        setState(state, { payload }) {
            const newState = {
                ...state,
                ...payload,
            };

            return newState;
        },
    },
    effects: {
        *loadStorage(_, { call, put }) {
            const user = yield call(load, { key: 'user' });
            yield put({
                type: 'setState',
                payload: {
                    loging: true,
                    user: user,
                },
            });
        },
        *login({ payload, callback }, { call, put }) {
            const { data, status, msg } = yield call(axios.post, REQUEST_URL, payload);
            if (status === 100) {
                yield put({
                    type: 'setState',
                    payload: {
                        loging: true,
                        user: data,
                    },
                });
                storage.save({
                    key: 'user', // 注意:请不要在key中使用_下划线符号!
                    data: data,
                });
                if (callback) {
                    callback();
                }
            } else {
                Toast.show(msg, {
                    duration: Toast.durations.LONG,
                    position: Toast.positions.CENTER,
                    shadow: true,
                    animation: true,
                });
            }
        },
        *logout(_, { put }) {
            yield put({
                type: 'setState',
                payload: {
                    loging: false,
                    user: undefined,
                },
            });
            storage.save({
                key: 'user', // 注意:请不要在key中使用_下划线符号!
                data: null,
            });
        },
    },
    subscriptions: {
        setup({ dispatch }) {
            dispatch({ type: 'loadStorage' });
        },
    },
};

export default PlayerModel;
